const express = require("express");
const { get, all } = require("./middle");
const { menuList } = require("./mockData");
// const fs = require("fs");

const app = express();

// 识别客户端传递过来的json数据
app.use(express.json());

// 允许跨域我们的端口号不一样，需要决绝跨域的问题，其实这里是可以使用webpack的nginx配置(目前已经使用nginx代替)
// app.use(require("cors")()); // 允许跨域

const mogoose = require("mongoose");
// const path = require("path");

// 连接数据库
mogoose.connect("mongodb://localhost:27017/test", function (err) {
  console.log(err);
});

// 如果mongoose放弃了重新连接的尝试，请终止该过程。
mogoose.connection.on("reconnectFailed", () => {
  process.nextTick(() => {
    throw new Error("Mongoose 无法重新连接到 MongoDB 服务器");
  });
});

//监听数据库连接状态
mogoose.connection.once("open", () => {
  console.log("数据库连接成功……");
});
mogoose.connection.once("close", () => {
  console.log("数据库断开……");
});

// token校验
app.use((req, res, next) => {
  console.log("🚀🚀🚀");
  // const err = req.headers["im-token"] !== "12345" ? "token 失效" : "";
  next();
});

app.use((req, res, next) => {
  console.log("🚀🚀");
  next();
});

app.use((req, res, next) => {
  console.log("🚀");
  next();
});

app.get("/", async (req, res) => {
  // const logSrc = path.resolve(__dirname, "./log.txt");
  // const log = fs.readFileSync(logSrc, "utf8", (err, data) => {
  //   return data;
  // });
  // res.send(log);
  res.send("localhost:3000 --- server online🚀🚀🚀");
});

function createDataTime() {
  return new Date();
}

// 建立模型
const Article = mogoose.model(
  "Article",
  new mogoose.Schema({
    title: { type: String },
    content: { type: String },
    createAt: { type: String, default: createDataTime() },
  })
);

// 新增文章的接口
app.post("/api/article", async (req, res) => {
  // 创建一条新的artcle数据
  const article = await Article.create(req.body);
  // 回传客户端，创建成功的信息
  res.send({ code: 200, data: article, msg: "" });
});

// 获取文章列表
app.get("/api/article/list", async (req, res, next) => {
  try {
    const article = await Article.find();
    res.send({ code: 200, data: article, msg: "" });
  } catch (err) {
    console.log(err);
    next("出错啦");
  }
});

// 获取文章详情
app.get("/api/article/detail/:id", async (req, res) => {
  const article = await Article.findById(req.params.id);
  res.send({ code: 200, data: article, msg: "" });
});

// : 表示是动态的id
app.delete("/api/article/delete/:id", async (req, res) => {
  await Article.findByIdAndDelete(req.params.id);
  res.send({ code: 200, data: true, msg: "" });
});

// 修改文章
app.put("/api/article/edit", async (req, res) => {
  const { id } = req.body;
  delete req.body.id;
  const article = await Article.findByIdAndUpdate(id, req.body);
  res.send({ code: 200, data: article, msg: "保存成功" });
});

/*** 使用中间件进行多个接口调用资源聚合 */
app.get("/api/user/list", async (req, res) => {
  const users = [{ name: "1111" }, { name: "2222" }];
  res.send({ code: 200, data: users, msg: "" });
});

app.get("/api/user/list2", async (req, res) => {
  const users = [{ name: "3333" }, { name: "44444" }];
  res.send({ code: 200, data: users, msg: "" });
});

app.get("/api/user", async (req, res) => {
  const user1 = get({ url: "http://localhost:3000/api/user/list" });
  const user2 = get({ url: "http://localhost:3000/api/user/list2" });
  const userRes = await all([user1, user2]);
  const user = userRes.reduce((cur, next) => cur.data.concat(next.data));
  res.send({ code: 200, data: user, msg: "" });
});

app.get("/api/information", async (req, res) => {
  res.send({ code: 200, data: menuList, msg: "" });
});

app.post("/api/login", async (req, res) => {
  res.send({ code: 200, data: "12345", msg: "" });
});

app.use((err, req, res, next) => {
  const handleError = (msg) => {
    res.status(500).json({
      code: 500,
      data: null,
      msg,
    });
  };
  err ? handleError(err) : next();
});

app.listen(3000, () => {
  console.log("listen 3000");
});
